//
// Created by kqbi on 2020/2/10.
//

#include "Config.h"
#include "Utils/Logger.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "Utils/Util.h"

#ifdef _WIN32

#include <windows.h>

#endif

Config::Config() {

}

Config::~Config() {

}

Config *Config::getInstance() {
    static Config config;
    return &config;
}

bool Config::init() {
    std::string dir = exeDir();
    if (!parseConfigInfo((dir + "config.ini").data())) {
        return false;
    }

    Logger::Instance().Init("fpms.log", 0, 0, 50, 5);
    return true;
}

bool Config::parseConfigInfo(const char *path) {
    boost::property_tree::ptree m_pt, httpserver_ini, mysql_ini, log_ini, tag_ini, base_ini;
    try {
        boost::property_tree::ini_parser::read_ini(path, m_pt);
        httpserver_ini = m_pt.get_child("http");
        _httpServerInfo.setPort(httpserver_ini.get<int>("port"));

        mysql_ini = m_pt.get_child("database");
        _dataBaseInfo.setIsMysql(mysql_ini.get<std::string>("ismysql"));
        _dataBaseInfo.setDatabaseIp(mysql_ini.get<std::string>("databaseip"));
        _dataBaseInfo.setDatabasePort(mysql_ini.get<int>("databaseport"));
        _dataBaseInfo.setDatabaseName(mysql_ini.get<std::string>("databasename"));
        _dataBaseInfo.setDatabaseUserName(mysql_ini.get<std::string>("databaseusername"));
        _dataBaseInfo.setDatabasePassword(mysql_ini.get<std::string>("databasepassword"));

        log_ini = m_pt.get_child("log");
        _logInfo.setLogType(log_ini.get<int>("logtype"));
        _logInfo.setLogLevel(log_ini.get<int>("loglevel"));
        _logInfo.setMaxFileSize(log_ini.get<std::string>("maxfilesize"));
        _logInfo.setMaxBackupIndex(log_ini.get<std::string>("maxbackupindex"));

        tag_ini = m_pt.get_child("tag");
        setTagInfo(tag_ini.get<std::string>("tag"));
        std::cout << "parseConfigInfo: " << getTagInfo() << std::endl;
        base_ini = m_pt.get_child(getTagInfo().c_str());
        _baseInfo.setAppId(base_ini.get<std::string>("APPID"));
        _baseInfo.setSdkKey(base_ini.get<std::string>("SDKKEY"));
        _baseInfo.setActiveKey(base_ini.get<std::string>("ACTIVE_KEY"));
        _baseInfo.setRgbLiveThreshold(base_ini.get<std::string>("rgbLiveThreshold"));
        _baseInfo.setIrLiveThreshold(base_ini.get<std::string>("irLiveThreshold"));
        _baseInfo.setRgbCameraId(base_ini.get<std::string>("rgbCameraId"));
        _baseInfo.setIrCameraId(base_ini.get<std::string>("irCameraId"));
        _baseInfo.setFilePath(base_ini.get<std::string>("filepath"));
    } catch (std::exception &e) {
        std::cout << "parseConfigInfo " << e.what() << std::endl;
        return false;
    }
    return true;
}

std::string Config::getTagInfo() {
    return _tagInfo;
}

void Config::setTagInfo(std::string tagInfo) {
    _tagInfo = tagInfo;
}